//
//  MarketViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/4.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "MarketViewController.h"
#import "MarketHeaderCell.h"
#import "MarketTypesCell.h"
#import "MarketPaimaiCell.h"
#import "MarketGoodsCell.h"
#import "MMMarketNew.h"
#import "MMMarketType.h"
#import "TitleView.h"
#import "MarketSearchViewController.h"
#import "GoodDetailViewController.h"
#import "PaiGoodDetailViewController.h"
#import "MarketTypeViewController.h"
#import "MsgCenterViewController.h"
#import "PaiGoodListViewController.h"
#import "OYCountDownManager.h"
#import <HyphenateLite/HyphenateLite.h>

@interface MarketViewController () <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, MarketGoodCellDelegate, MarketTypesDelegate, MarketPaimaiDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) NSInteger newcount;
@property (assign, nonatomic) NSInteger worthcount;
@property (strong, nonatomic) TitleView *titleView;
@property (strong, nonatomic) UIButton *noticebtn;
@property (strong, nonatomic) UILabel *noticecount;

@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) BOOL pageToEnd;

@end

@implementation MarketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.titleView = [[TitleView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    self.titleView.backgroundColor = [UIColor clearColor];
    
    UISearchBar *searchbar = [[UISearchBar alloc]initWithFrame:CGRectMake(10, 7, ScreenWidth - 65, 30)];
    searchbar.searchBarStyle = UISearchBarStyleDefault;
    searchbar.placeholder = @"搜索你喜欢的产品";
    searchbar.layer.masksToBounds = YES;
    searchbar.layer.cornerRadius = 4.f;
    searchbar.delegate = self;
    [self.titleView addSubview:searchbar];
    
    self.noticebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.noticebtn.frame = CGRectMake(ScreenWidth - 40, 12, 20, 20);
    [self.noticebtn setBackgroundImage:[UIImage imageNamed:@"topnotice.png"] forState:UIControlStateNormal];
    [self.noticebtn addTarget:self action:@selector(clickNotice:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *clickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    clickbtn.frame = CGRectMake(ScreenWidth - 50, 0, 40, 44);
    [self.titleView addSubview:clickbtn];
    [clickbtn addTarget:self action:@selector(clickNotice:) forControlEvents:UIControlEventTouchUpInside];
    
    self.noticecount = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 10, 10)];
    self.noticecount.font = [FontTool fontWithSize:10];
    self.noticecount.textAlignment = NSTextAlignmentCenter;
    self.noticecount.textColor = [UIColor whiteColor];
    self.noticecount.backgroundColor = [UIColor colorWithHexString:@"0EA1B6"];
    self.noticecount.layer.masksToBounds = YES;
    self.noticecount.layer.cornerRadius = 5.f;
    self.noticecount.text = @"1";
    self.noticecount.hidden = YES;
    self.noticecount.userInteractionEnabled = NO;
    [self.noticebtn addSubview:self.noticecount];
    [self.titleView addSubview:self.noticebtn];
    
    self.navigationItem.titleView = self.titleView;
    
    NSDictionary *dict = [[TMCache sharedCache] objectForKey:@"AllMarketData"];
    [MARKETDATA readDataFromCache:dict];
    [self.tableView reloadData];
    
    self.pageToEnd = NO;
    self.page = 1;
    [self loadNetworkData];
    
    //
    [kCountDownManager start];
    
    [self addRefreshHeader:self.tableView];
    [self addLoadMoreFooter:self.tableView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    [self getMsgCount];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)clickNotice:(id)sender {
    MsgCenterViewController *vc = [[MsgCenterViewController alloc] initWithNibName:@"MsgCenterViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    MarketSearchViewController *vc = [[MarketSearchViewController alloc] initWithNibName:@"MarketSearchViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    return NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (4 + self.newcount + self.worthcount);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 188;
    } else if (indexPath.row == 1) {
        return 175;
    } else if (indexPath.row == 2) {
        return 210;
    } else if (indexPath.row == 3) {
        return 210;
    } else if (indexPath.row > 3 && indexPath.row <= (3 + self.newcount)) {
        return 307;
    } else if (indexPath.row > (3 + self.newcount) && indexPath.row <= (3 + self.newcount + self.worthcount)) {
        if (indexPath.row == 4 + self.newcount)
            return 307;
        return 257;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        MarketHeaderCell *cell = GET_CELL(MarketHeaderCell, @"MarketHeaderCell");
        cell.vc = self;
        [cell fillData];
        return cell;
    } else if (indexPath.row == 1) {
        MarketTypesCell *cell = GET_CELL(MarketTypesCell, @"MarketTypesCell");
        [cell contentWithArray:MARKETDATA.marketTypes];
        cell.delegate = self;
        return cell;
    } else if (indexPath.row == 2) {
        MarketPaimaiCell *cell = GET_CELL(MarketPaimaiCell, @"MarketPaimaiCell");
        cell.title.text = @"人气拍卖";
        [cell contentWithArray:MARKETDATA.marketRenqi];
        cell.delegate = self;
        return cell;
    } else if (indexPath.row == 3) {
        MarketPaimaiCell *cell = GET_CELL(MarketPaimaiCell, @"MarketPaimaiCell");
        cell.title.text = @"0元起拍";
        cell.delegate = self;
        [cell contentWithArray:MARKETDATA.marketZero];
        return cell;
    } else if (indexPath.row > 3 && indexPath.row <= (3 + self.newcount)) {
        MarketGoodsCell *cell = GET_CELL(MarketGoodsCell, @"MarketGoodsCell");
        MMMarketNew *ldata = nil;
        MMMarketNew *rdata = nil;
        if (MARKETDATA.marketNew.count > (indexPath.row - 4)) {
            ldata = [MARKETDATA.marketNew objectAtIndex:(indexPath.row - 4)];
        }
        if (MARKETDATA.marketNew.count > (indexPath.row - 4 + 1)) {
            rdata = [MARKETDATA.marketNew objectAtIndex:(indexPath.row - 4 + 1)];
        }
        cell.titleH.constant = 50;
        cell.title.hidden = NO;
        cell.title.text = @"新品推荐";
        cell.type = IMarketGoodCellNew;
        cell.index = indexPath.row - 4;
        cell.delegate = self;
        [cell fillWithData:ldata right:rdata];
        return cell;
    } else if (indexPath.row > (3 + self.newcount) && indexPath.row <= (3 + self.newcount + self.worthcount)) {
        MarketGoodsCell *cell = GET_CELL(MarketGoodsCell, @"MarketGoodsCell");
        MMMarketNew *ldata = nil;
        MMMarketNew *rdata = nil;
        NSInteger from = (indexPath.row - 4 - self.newcount);
        if (MARKETDATA.marketWorth.count > from * 2) {
            ldata = [MARKETDATA.marketWorth objectAtIndex:(from * 2)];
        }
        if (MARKETDATA.marketWorth.count > from * 2 + 1) {
            rdata = [MARKETDATA.marketWorth objectAtIndex:(from * 2 + 1)];
        }
        if (indexPath.row == 4 + self.newcount) {
            cell.titleH.constant = 50;
            cell.title.hidden = NO;
        } else {
            cell.titleH.constant = 0;
            cell.title.hidden = YES;
        }
        
        cell.title.text = @"值得买";
        cell.type = IMarketGoodCellWorth;
        cell.index = from;
        cell.delegate = self;
        [cell fillWithData:ldata right:rdata];
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (void)clickMarketTypesOne:(NSInteger)index {
    MMMarketType *one = [MARKETDATA.marketTypes objectAtIndex:index];
    MarketTypeViewController *vc = [[MarketTypeViewController alloc] initWithNibName:@"MarketTypeViewController" bundle:nil];
    vc.marketTypeName = one.type_name;
    vc.marketTypeid = one.theid;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)clickMarketPaimaiOne:(NSInteger)index title:(NSString *)title {
    if ([title isEqualToString:@"人气拍卖"]) {
        MMMarketPai *one = [MARKETDATA.marketRenqi objectAtIndex:index];
        PaiGoodDetailViewController *vc = [[PaiGoodDetailViewController alloc] initWithNibName:@"PaiGoodDetailViewController" bundle:nil];
        vc.gooddata = one;
        vc.goodname = one.goods_name;
        vc.productId = one.goods_id;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        MMMarketPai *one = [MARKETDATA.marketZero objectAtIndex:index];
        PaiGoodDetailViewController *vc = [[PaiGoodDetailViewController alloc] initWithNibName:@"PaiGoodDetailViewController" bundle:nil];
        vc.gooddata = one;
        vc.goodname = one.goods_name;
        vc.productId = one.goods_id;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)clickMarketGoodCell:(NSInteger)index isLeft:(BOOL)clickLeft myType:(MarketGoodCellType)type {
    MMMarketNew *gooddata = nil;
    if (clickLeft) {
        if (type == IMarketGoodCellNew) {
            gooddata = [MARKETDATA.marketNew objectAtIndex:index];
        } else {
            gooddata = [MARKETDATA.marketWorth objectAtIndex:index * 2];
        }
    } else {
        if (type == IMarketGoodCellNew) {
            gooddata = [MARKETDATA.marketNew objectAtIndex:index + 1];
        } else {
            gooddata = [MARKETDATA.marketWorth objectAtIndex:index * 2 + 1];
        }
    }
    
    if (gooddata) {
        [[GoToManager sharedGoToManager] go:self type:ToGoodDetail data:gooddata];
    }
}

- (void)getMsgCount {
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = [NSString stringWithFormat:@"%@/sys/index/message/count", APIYIGOU];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSInteger count = [[dict objectForKey:@"data"] integerValue];
        self.noticecount.text = [NSString stringWithFormat:@"%ld", count];
        if (count == 0) {
            self.noticecount.hidden = YES;
        } else {
            self.noticecount.hidden = NO;
        }
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
    }];
}

- (void)loadNetworkData {
    self.page = 1;
    self.pageToEnd = NO;
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/product/jishiIndex?page=%ld", APIYIGOU, self.page];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        [MARKETDATA initWithDict:dict];
        self.newcount = MARKETDATA.marketNew.count / 2 + MARKETDATA.marketNew.count % 2;
        self.worthcount = MARKETDATA.marketWorth.count / 2 + MARKETDATA.marketWorth.count % 2;
        [self.tableView reloadData];
        self.page += 1;
        [kCountDownManager reload];
        [self.tableView.header endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.header endRefreshing];
    }];
}

- (void)refresh {
    [super refresh];
    [self loadNetworkData];
}

- (void)loadMore {
    [super loadMore];
    if (self.pageToEnd) {
        [ViewFactory showInfoMsg:@"没有下一页了！"];
        [self.tableView.footer endRefreshing];
        return;
    }
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/product/jishiIndex?page=%ld", APIYIGOU, self.page];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        self.page += 1;
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        NSDictionary *data = [dict objectForKey:@"data"];
        NSDictionary *zdm = [data objectForKey:@"zdm"];
        NSArray *array = [zdm objectForKey:@"list"];
        if (array.count == 0) {
            self.pageToEnd = YES;
        }
        [JSONModel addDatasFromDict:zdm withModel:@"MMMarketNew" forKey:@"list" target:MARKETDATA.marketWorth isAppend:YES];
        self.worthcount = MARKETDATA.marketWorth.count / 2 + MARKETDATA.marketWorth.count % 2;
        [self.tableView reloadData];
        [kCountDownManager reload];
        [self.tableView.footer endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [self.tableView.footer endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [self.tableView.footer endRefreshing];
    }];
}

@end
